//express
const express = require("express");
const router = express.Router();

//处理formdata
const bodyParser = require("body-parser");
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({
  extended: false,
});

//处理node request请求
const request = require("request");

const jwt = require("jsonwebtoken");
//这个是jsonwebtoken中的方法，我又进行了二次加工。

//微信小程序设置
const wx = require("./wxconfig.json"); //文件中存储了appid 和 secret

//数据库
// const datebase = require('./dbconfig.json') //文件中存储了数据库地址
// const mongodb = require('mongodb');
// const MongoClient = mongodb.MongoClient;
console.log(111);
//路由
router.post("/info", urlencodedParser, (req, res) => {
  //拿到前台给的code后，发送请求
  console.log(req);
  if (req.body.code) {
    let options = {
      method: "POST",
      url: "https://api.weixin.qq.com/sns/jscode2session",

      formData: {
        appid: wx.appid,
        secret: wx.secret,
        js_code: req.body.code,
        grant_type: "authorization_code",
      },
    };

    request(options, (error, response, body) => {
      if (error) {
        //请求异常时，返回错误信息
        console.log("error");
        res.json({
          status: "error",
          code: "出错了",
        });
      } else {
        console.log("success");
        //返回值的字符串转JSON
        let _data = JSON.parse(body);
        console.log(_data);
        // console.log(jwt);
        const secret = "abc";
        let token = jwt.sign(
          {
            name: _data.openid,
          },
          secret
        );
        console.log("token===", token);
        res.json({
          // info: Object.assign(_data,token)
          code: "200",
          info: _data,
          token,
        });
      }
    });
  } else {
    res.json({
      status: "error",
      code: "000",
    });
  }
});

module.exports = router;
